package com.springboot.base.controller;

import com.springboot.base.common.*;
import com.springboot.base.model.User;
import com.springboot.base.request.RegisterReq;
import com.springboot.base.request.UserLoginReq;
import com.springboot.base.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * @author meiguangya
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    HttpServletRequest httpServletRequest;

    public static final String CURRENT_USER_SESSION = "currentUserSession";


    @RequestMapping("/{id}")
    public ServerResponse getUser(@PathVariable("id") Integer id) throws BusinessException {
        User u = userService.getById(id);
        if (u == null) {
            throw new BusinessException(EmBusinessError.NO_OBJECT_FOUND);
        } else {
            return ServerResponse.createBySuccessData(u);
        }
    }

    @PostMapping("/register")
    public ServerResponse register(@Valid @RequestBody RegisterReq registerReq, BindingResult bindingResult) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {

        if (bindingResult.hasErrors()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,
                    CommonUtil.processErrorString(bindingResult));
        }

        User registerUser = new User(registerReq);
        registerUser = userService.register(registerUser);
        return ServerResponse.createBySuccessData(registerUser);

    }

    @PostMapping("/login")
    public ServerResponse login(@RequestBody UserLoginReq loginReq) throws UnsupportedEncodingException, NoSuchAlgorithmException, BusinessException {
        User u = userService.login(new User(loginReq));
        if (u == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_FOUND);
        }
        //存入session中
        httpServletRequest.getSession().setAttribute(CURRENT_USER_SESSION, u);

        return ServerResponse.createBySuccessData(u);
    }

    @PostMapping("/logout")
    public ServerResponse logout() {
        httpServletRequest.getSession().invalidate();
        return ServerResponse.createBySuccess();
    }

    /**
     * 获取当前用户信息
     */
    @RequestMapping("/getcurrentuser")
    public ServerResponse getCurrentUser() {
        User u = (User) httpServletRequest.getSession().getAttribute(CURRENT_USER_SESSION);
        return ServerResponse.createBySuccessData(u);
    }


}
